package abc.base;

import abc.model.ResponseData;
import abc.model.PageInfo;
import abc.model.ResponseData;
import abc.utils.EncryptionUtil;
import abc.utils.StringUtil;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

public interface IBaseResponse {

    public final String ENCODING = "UTF-8";

    default ResponseData<String> success() {
        return this.result(0, "OK", null, null);
    }

    default <T> ResponseData<T> success(T data) {
        return this.result(0, "OK", data, null);
    }

    default ResponseData<String> message(String text) {
        return this.result(0, text, null, null);
    }

    default <T> ResponseData<T> success(T data, PageInfo pageInfo) {
        return this.result(0, "OK", data, pageInfo);
    }

    default ResponseData error(String message) {
        return this.result(-1, message, "", null);
    }

    default ResponseData error(int code, Exception e) {

        if(StringUtil.isEmpty(e.getMessage())) {
            return this.result(code, e.toString(), "", null);
        }
        return this.result(code, e.getMessage(), "", null);
    }

    default ResponseData error(int code, String message) {
        return this.result(code, message, "", null);
    }

    default  <T> ResponseData<T> result(int code, String message, T data, PageInfo pageInfo) {
        ResponseData<T> result = new ResponseData<T>();

        result.setStatus(code);
        result.setMessage(message);
        result.setData(data);
        result.setPageInfo(pageInfo);

        return result;
    }

    default String base64Encode(String data) throws Exception {
        return EncryptionUtil.base64Encode(data, ENCODING);
    }

    default String base64EncodeSafe(String data) throws Exception {
        return EncryptionUtil.base64EncodeSafe(data, ENCODING);
    }

    default String base64Decode(String data) throws Exception {
        return EncryptionUtil.base64Decode(data, ENCODING);
    }
}
